package com.ytjj.qmyx.mall.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.mall.mapper.OrdersDao;
import com.ytjj.qmyx.mall.model.ComplaintsHistoryResponse;
import com.ytjj.qmyx.mall.model.PayConfig;
import com.ytjj.qmyx.mall.model.request.WxComplaintsCallBackRequest;
import com.ytjj.qmyx.mall.model.WxComplaintsListRequest;
import com.ytjj.qmyx.mall.model.WxComplaintsReplyRequest;
import com.ytjj.qmyx.mall.model.response.WxComplaintsCallBackResponse;
import com.ytjj.qmyx.mall.model.WxComplaintsListResponse;
import com.ytjj.qmyx.mall.service.ComplaintsService;
import com.ytjj.qmyx.mall.utils.WxAPIV3AesUtil;
import com.ytjj.qmyx.mall.utils.WxPayServiceUtil;
import com.ytjj.qmyx.mall.utils.WxpayV3Util;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 *微信投诉
 * @author
 */
@RestController
@RequestMapping("/complaints")
@Slf4j
@RefreshScope
public class ComplaintsController extends BaseController {

    private static final String COMPLAINTS_URL = "/v3/merchant-service/complaints-v2";

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private ComplaintsService complaintsService;

    @Resource
    private RedisService redisService;

    /**
     * 查询投诉单列表
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/wxComplaintsV3List")
    public CommonResult<CommonPage> wxComplaintsV3List(@RequestBody WxComplaintsListRequest request) throws Exception{
        PayConfig payConfig = ordersDao.getPayConfig("guchuangh5", "H5", "MWEB", "NORMAL");
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);

        String totalQuery = String.format("?limit=%s&offset=0&begin_date=%s&end_date=%s&complainted_mchid=%s",request.getPageSize(),
                request.getBeginTime(),request.getEndTime(),payConfig.getMchId());
        JSONObject totalJsonObject = WxpayV3Util.queryComplaintsV3(COMPLAINTS_URL + totalQuery, wxPayService.getConfig());

        String query = String.format("?limit=%s&offset=%s&begin_date=%s&end_date=%s&complainted_mchid=%s",request.getPageSize(),
                request.getPageNum() == 1 ? 0: (request.getPageNum()-1) * request.getPageSize() ,request.getBeginTime(),request.getEndTime(),payConfig.getMchId());
        JSONObject jsonObject = WxpayV3Util.queryComplaintsV3(COMPLAINTS_URL + query, wxPayService.getConfig());
        JSONArray data = jsonObject.getJSONArray("data");
        List<WxComplaintsListResponse> list = new ArrayList<>();
        for (Object datum : data) {
            JSONObject datum1 = (JSONObject) datum;
            if (StringUtils.isNotBlank(datum1.getString("payer_phone"))) {
                datum1.put("payer_phone",WxpayV3Util.rsaDecryptOAEP(datum1.getString("payer_phone"),payConfig.getPrivateKeyPath()));
            }
            JSONArray complaint_order_info = datum1.getJSONArray("complaint_order_info");
            if (null != complaint_order_info) {
                JSONObject jsonObject1 = (JSONObject) complaint_order_info.get(0);
                BigDecimal amount = jsonObject1.getBigDecimal("amount");
                datum1.put("amount",amount);
            }
            WxComplaintsListResponse response = new WxComplaintsListResponse(datum1);
            list.add(response);
        }
        CommonPage<WxComplaintsListResponse> page = CommonPage.restPage(list);
        Integer total = totalJsonObject.getInteger("total_count");
        Integer totalPage = (total % request.getPageSize()) > 0 ? (total / request.getPageSize()) + 1 : (total / request.getPageSize());
        page.setTotal(total.longValue());
        page.setTotalPage(totalPage);
        return CommonResult.success(page);
    }



//    public static void main(String[] args) throws Exception{
//        String s="{\"data\":[{\"problem_description\":\"不满意商家的商品或服务\",\"complaint_media_list\":[{\"media_type\":\"USER_COMPLAINT_IMAGE\",\"media_url\":[\"https://api.mch.weixin.qq.com/v3/merchant-service/images/ChsyMDAwMDAwMjAyMzA5MzAxODAxMTc4NDMzMDMYACDKm%2BepBigBMAE4AQ%3D%3D\"]}],\"service_order_info\":[],\"payer_phone\":\"twtwVuthO5PisXE4SfKuTKh9oeQD5jroQYKbnsOdWA3APTBcz5aC3mz+xBrJoWT1AVrNs5z3iojeMeOM3xKNZKMyQ1M/14k6FEFteI9hNl6QcvwrDvpuGjBmiLAtdHcwcZJOIKJ5dvSPXhJuF1pB8ddJwJisu4OpyxoOFQdmMu73VcbnzTd5DSN9d80gh44qOPMNeQcdcm7NTHUG4JnUr2VRivN44fIWgLpRExv+M1TM6mXC5t7YQVHLtfsEcoawzbKoRnNOFZJQ4HZrW5BmQNBhOCyIFphQFE3xaNMqcc1l6WgSW3vgOaLSMwP37OgS2yPOynGuwzEVkAnOF+oa9w==\",\"user_tag_list\":[],\"complaint_full_refunded\":true,\"complaint_id\":\"200000020230930180117843303\",\"incoming_user_response\":false,\"complaint_detail\":\"退货货品不喜欢，要求退货\",\"complaint_order_info\":[{\"transaction_id\":\"4200001966202309252744113800\",\"amount\":12900,\"out_trade_no\":\"PAY2023092511182197689767\"}],\"problem_type\":\"OTHERS\",\"complaint_time\":\"2023-09-30T18:44:04+08:00\",\"complaint_state\":\"PROCESSED\",\"user_complaint_times\":1},{\"problem_description\":\"其他问题\",\"complaint_media_list\":[{\"media_type\":\"USER_COMPLAINT_IMAGE\",\"media_url\":[\"https://api.mch.weixin.qq.com/v3/merchant-service/images/ChsyMDAwMDAwMjAyMzA5MzAxNDAxMTc3NTkzMjEYACDKm%2BepBigBMAE4AQ%3D%3D\",\"https://api.mch.weixin.qq.com/v3/merchant-service/images/ChsyMDAwMDAwMjAyMzA5MzAxNDAxMTc3NTkzMjEYASDKm%2BepBigBMAE4AQ%3D%3D\",\"https://api.mch.weixin.qq.com/v3/merchant-service/images/ChsyMDAwMDAwMjAyMzA5MzAxNDAxMTc3NTkzMjEYAiDKm%2BepBigBMAE4AQ%3D%3D\",\"https://api.mch.weixin.qq.com/v3/merchant-service/images/ChsyMDAwMDAwMjAyMzA5MzAxNDAxMTc3NTkzMjEYAyDKm%2BepBigBMAE4AQ%3D%3D\"]}],\"service_order_info\":[],\"payer_phone\":\"wjqagZ3jSAgBkQ3Z7Wikeahx25vOfc74Aa0WFhAsbX5IDntypltwgowukhzJSs2wno+Dzb+pOb5BqAtuq13G6vKwITFKytC4ocqU6dCMBY7PjzH8uYDS8/PEsQR477B4jVzvpenog29k6WVjZOewR3QqvslDjT6ghGYC5WIKjqBfSNxx22GFUodwfdfvvK/vbPjiVFq0dNvZUZaZSLJRIWCl2WQvLALWfedvqMEFcqkAzD/X8yr7UYlGjrXJ8GvLI1fZHv6qtkfgie1OedR4EvPT0gvjM1+WCcBkhvzTkOZcFEoAyeB2I03o4myOaZc/QitiiB3/TA8JZxgLYfx4fA==\",\"user_tag_list\":[],\"complaint_full_refunded\":false,\"complaint_id\":\"200000020230930140117759321\",\"incoming_user_response\":false,\"complaint_detail\":\"你们的手表是否是非.正品货.外围;时和内分时都不标准.是什么表真是笑话.小孩都看的出来.还好意思拿出来拍卖。\",\"complaint_order_info\":[{\"transaction_id\":\"4200001814202309183751007028\",\"amount\":12800,\"out_trade_no\":\"PAY2023091811190320313498\"}],\"problem_type\":\"OTHERS\",\"complaint_time\":\"2023-09-30T14:05:43+08:00\",\"complaint_state\":\"PROCESSED\",\"user_complaint_times\":1}],\"offset\":1,\"limit\":2}";
//        JSONObject jsonObject = JSONObject.parseObject(s);
//        JSONArray data = jsonObject.getJSONArray("data");
//        for (Object datum : data) {
//            JSONObject datum1 = (JSONObject) datum;
//            datum1.put("payer_phone",WxpayV3Util.rsaDecryptOAEP(datum1.getString("payer_phone"),""));
//            JSONArray complaint_order_info = datum1.getJSONArray("complaint_order_info");
//            if (null != complaint_order_info) {
//                JSONObject jsonObject1 = (JSONObject) complaint_order_info.get(0);
//                BigDecimal amount = jsonObject1.getBigDecimal("amount");
//                datum1.put("amount",amount);
//            }
//            WxComplaintsListResponse response = new WxComplaintsListResponse(datum1);
//            System.out.println("response = " + response);
//        }
//        System.out.println("jsonObject = " + jsonObject);
//    }

    /**
     * 查询投诉单详情
     * @param complaintId
     * @return
     * @throws Exception
     */
    @GetMapping("/wxComplaintsV3Detail")
    public CommonResult<Object> wxComplaintsV3Detail(@RequestParam String complaintId) throws Exception{
        return CommonResult.success(complaintsService.queryComplaintsV3(complaintId));
    }

    /**
     * 查询投诉单协商历史
     * @param complaintId
     * @return
     * @throws Exception
     */
    @GetMapping("/wxComplaintsV3History")
    public CommonResult<List<ComplaintsHistoryResponse>> wxComplaintsV3History(@RequestParam("complaintId") String complaintId) throws Exception{
        return CommonResult.success(complaintsService.wxComplaintsV3History(complaintId));
    }

    /**
     * 回复用户
     * @param replyRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/wxComplaintsV3Response")
    public CommonResult<Object> wxComplaintsV3Response(@RequestBody WxComplaintsReplyRequest replyRequest) throws Exception{
        JSONObject jsonObject =  complaintsService.wxComplaintsV3Response(replyRequest);
        return CommonResult.success(jsonObject);
    }


    /**
     * 反馈处理完成
     * @param complaintId
     * @return
     * @throws Exception
     */
    @GetMapping("/wxComplaintsV3Complete")
    public CommonResult<JSONObject> wxComplaintsV3Complete(@RequestParam("complaintId") String complaintId,
                                                           @RequestParam("adminId") Integer adminId) throws Exception{
        return CommonResult.success(complaintsService.wxComplaintsV3Complete(complaintId,adminId));
    }

    /**
     * 获取微信图片
     * @param media_url
     * @return
     * @throws Exception
     */
    @GetMapping("/downLoadComplaintsHistoryImg")
    public CommonResult<List<String>> downLoadComplaintsHistoryImg(@RequestParam("media_url") String media_url) throws Exception{
        PayConfig payConfig = ordersDao.getPayConfig("guchuangh5", "H5", "MWEB", "NORMAL");
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        return CommonResult.success(complaintsService.downLoadComplaintsHistoryImg(Lists.newArrayList(media_url),wxPayService.getConfig()));
    }

    /**
     * 商户上传反馈图片
     */

    @PostMapping("/upload")
    public CommonResult <String>getImgUrl(@RequestParam("fileUrl") String  fileUrl,@RequestParam("complaintId") String complaintId) throws Exception{
        return CommonResult.success(complaintsService.complaintsImagesUpLoad(fileUrl,complaintId));
    }

    /**
     * 创建投诉通知回调
     * @param url
     * @return
     * @throws Exception
     */
    @GetMapping("/createWxComplaintsV3Notifications")
    public CommonResult<Object> createWxComplaintsV3Notifications(@RequestParam("url") String url,@RequestParam("tradeType") String tradeType,String company,String type) throws Exception{
        PayConfig payConfig = ordersDao.getPayConfig(company, type, tradeType, "NORMAL");
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String postUrl = "/v3/merchant-service/complaint-notifications";
        JSONObject requestJsonObject = new JSONObject();
        requestJsonObject.put("url",url);
        log.info("创建投诉通知回调参数:{}",postUrl);
        JSONObject jsonObject = WxpayV3Util.operationComplaintsV3(postUrl, requestJsonObject,wxPayService.getConfig(),"post");
        log.info("创建投诉通知回调返回:{}",jsonObject.toJSONString());
        return CommonResult.success(jsonObject);
    }


    /**
     * 查询投诉通知回调
     * @return
     * @throws Exception
     */
    @GetMapping("/queryWxComplaintsV3Notifications")
    public CommonResult<Object> queryWxComplaintsV3Notifications(@RequestParam("tradeType") String tradeType,String company,String type) throws Exception{
        PayConfig payConfig = ordersDao.getPayConfig(company, type, tradeType, "NORMAL");
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String queryUrl = "/v3/merchant-service/complaint-notifications";
        log.info("查询投诉通知回调参数:{}",queryUrl);
        JSONObject jsonObject = WxpayV3Util.queryComplaintsV3(queryUrl,wxPayService.getConfig());
        log.info("查询投诉通知回调返回:{}",jsonObject.toJSONString());
        return CommonResult.success(jsonObject);
    }

    /**
     * 更新投诉通知回调
     */
    @GetMapping("/updateWxComplaintsV3Notifications")
    public CommonResult<Object> updateWxComplaintsV3Notifications(@RequestParam("url") String url,@RequestParam("tradeType") String tradeType,String company,String type) throws Exception{
        PayConfig payConfig = ordersDao.getPayConfig(company, type, tradeType, "NORMAL");
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String putUrl = "/v3/merchant-service/complaint-notifications";
        JSONObject requestJsonObject = new JSONObject();
        requestJsonObject.put("url",url);
        log.info("更新投诉通知回调参数:{}",putUrl);
        JSONObject jsonObject = WxpayV3Util.operationComplaintsV3(putUrl, requestJsonObject,wxPayService.getConfig(),"put");
        log.info("更新投诉通知回调返回:{}",jsonObject.toJSONString());
        return CommonResult.success(jsonObject);
    }

    /**
     * 微信投诉通知回调
     */
    @PostMapping("/wxComplaintsV3CallBack")
    public String wxComplaintsV3CallBack(@RequestBody WxComplaintsCallBackRequest request) throws Exception{
        log.info("微信投诉通知回调通知,{}",JSONObject.toJSONString(request));
        try {
            if("COMPLAINT.CREATE".equals(request.getEvent_type()) ){
                log.info("微信投诉创建回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("guchuangh5", "H5", "MWEB", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("创建微信投诉通知返回,{}",decryptToString);
                Gson gson = new Gson();
                request.setMch_id(payConfig.getMchId());
                WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                complaintsService.createComplaints(request,response);

            } else if ("COMPLAINT.STATE_CHANGE".equals(request.getEvent_type())) {
                log.info("微信投诉状态变更回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("guchuangh5", "H5", "MWEB", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                String redisKey ="wx_complaints_callback" + decryptToString;
                String value = redisService.get(redisKey);
                if (StringUtils.isBlank(value)) {
                    Gson gson = new Gson();
                    WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                    complaintsService.updateComplaints(request,response);
                    redisService.set(redisKey,"1",60);
                }
            }
        }catch (Exception e){
            log.error("微信投诉创建或者修改失败Event_type:{},原因:{}",request.getEvent_type(),e.getMessage());
        }

        Map<String, String> feedbackMap = Maps.newHashMap();
        feedbackMap.put("code","SUCCESS");
        feedbackMap.put("message","成功");
        return JSONObject.toJSONString(feedbackMap);
    }


    /**
     * 微信投诉通知回调
     */
    @PostMapping("/wxComplaintsV3CallBackV2")
    public String wxComplaintsV3CallBackV2(@RequestBody WxComplaintsCallBackRequest request) throws Exception{
        log.info("微信投诉通知回调通知,{}",JSONObject.toJSONString(request));
        try {
            if("COMPLAINT.CREATE".equals(request.getEvent_type()) ){
                log.info("微信投诉创建回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("guchuangh5", "H5", "MWEB2", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("创建微信投诉通知返回,{}",decryptToString);
                Gson gson = new Gson();
                request.setMch_id(payConfig.getMchId());
                WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                complaintsService.createComplaints(request,response);

            } else if ("COMPLAINT.STATE_CHANGE".equals(request.getEvent_type())) {
                log.info("微信投诉状态变更回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("guchuangh5", "H5", "MWEB2", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("微信投诉状态变更回调通知返回,{}",decryptToString);
                String redisKey ="wx_complaints_callback" + decryptToString;
                String value = redisService.get(redisKey);
                if (StringUtils.isBlank(value)) {
                    Gson gson = new Gson();
                    WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                    complaintsService.updateComplaints(request,response);
                    redisService.set(redisKey,"1",60);
                }

            }
        }catch (Exception e){
            log.error("微信投诉创建或者修改失败Event_type:{},原因:{}",request.getEvent_type(),e.getMessage());
        }

        Map<String, String> feedbackMap = Maps.newHashMap();
        feedbackMap.put("code","SUCCESS");
        feedbackMap.put("message","成功");
        return JSONObject.toJSONString(feedbackMap);
    }

    /**
     * 微信小程序投诉通知回调
     */
    @PostMapping("/wxComplaintsV3CallBackV3")
    public String wxComplaintsV3CallBackV3(@RequestBody WxComplaintsCallBackRequest request) throws Exception{
        log.info("微信投诉通知回调通知,{}",JSONObject.toJSONString(request));
        try {
            if("COMPLAINT.CREATE".equals(request.getEvent_type()) ){
                log.info("微信投诉创建回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("platform", "APP", "JSAPI", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("创建微信投诉通知返回,{}",decryptToString);
                Gson gson = new Gson();
                request.setMch_id(payConfig.getMchId());
                WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                complaintsService.createComplaints(request,response);

            } else if ("COMPLAINT.STATE_CHANGE".equals(request.getEvent_type())) {
                log.info("微信投诉状态变更回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("platform", "APP", "JSAPI", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("微信投诉状态变更回调通知返回,{}",decryptToString);
                String redisKey ="wx_complaints_callback" + decryptToString;
                String value = redisService.get(redisKey);
                if (StringUtils.isBlank(value)) {
                    Gson gson = new Gson();
                    WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                    complaintsService.updateComplaints(request,response);
                    redisService.set(redisKey,"1",60);
                }

            }
        }catch (Exception e){
            log.error("微信投诉创建或者修改失败Event_type:{},原因:{}",request.getEvent_type(),e.getMessage());
        }

        Map<String, String> feedbackMap = Maps.newHashMap();
        feedbackMap.put("code","SUCCESS");
        feedbackMap.put("message","成功");
        return JSONObject.toJSONString(feedbackMap);
    }


    @PostMapping("/wxComplaintsV3CallBackV4")
    public String wxComplaintsV3CallBackV4(@RequestBody WxComplaintsCallBackRequest request) throws Exception{
        log.info("微信投诉通知回调通知,{}",JSONObject.toJSONString(request));
        try {
            if("COMPLAINT.CREATE".equals(request.getEvent_type()) ){
                log.info("微信投诉创建回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("platform", "H5", "JSAPI", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("创建微信投诉通知返回,{}",decryptToString);
                Gson gson = new Gson();
                request.setMch_id(payConfig.getMchId());
                WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                complaintsService.createComplaints(request,response);

            } else if ("COMPLAINT.STATE_CHANGE".equals(request.getEvent_type())) {
                log.info("微信投诉状态变更回调通知");
                PayConfig payConfig = ordersDao.getPayConfig("platform", "H5", "JSAPI", "NORMAL");
                byte[] key = payConfig.getWxKey().getBytes("UTF-8");
                WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
                String associated_data = request.getResource().getAssociated_data();
                String nonce = request.getResource().getNonce();
                String ciphertext = request.getResource().getCiphertext();
                String decryptToString = aesUtil.decryptToString(associated_data.getBytes("UTF-8"),nonce.getBytes("UTF-8"),ciphertext);
                log.info("微信投诉状态变更回调通知返回,{}",decryptToString);
                String redisKey ="wx_complaints_callback" + decryptToString;
                String value = redisService.get(redisKey);
                if (StringUtils.isBlank(value)) {
                    Gson gson = new Gson();
                    WxComplaintsCallBackResponse response = gson.fromJson(decryptToString, WxComplaintsCallBackResponse.class);
                    complaintsService.updateComplaints(request,response);
                    redisService.set(redisKey,"1",60);
                }

            }
        }catch (Exception e){
            log.error("微信投诉创建或者修改失败Event_type:{},原因:{}",request.getEvent_type(),e.getMessage());
        }

        Map<String, String> feedbackMap = Maps.newHashMap();
        feedbackMap.put("code","SUCCESS");
        feedbackMap.put("message","成功");
        return JSONObject.toJSONString(feedbackMap);
    }

}
